<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        @submit.native.prevent
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="业务系统" prop="applicationSystem">
          <el-select
            v-model="queryParams.applicationSystem"
            class="custom-select"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              class="custom-select"
              v-for="(item, index) in businessCodeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictLabel"
            >
              <span class="selectList">
                <common-marquee-text :content="item.dictLabel">
                </common-marquee-text>
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="实例名/服务名" prop="serviceName">
          <common-input
            v-model="queryParams.serviceName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据库名" prop="dbName">
          <common-input
            v-model="queryParams.dbName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="数据库组" prop="dbGroupId">
          <el-select
            v-model="queryParams.dbGroupId"
            clearable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in dbGroupList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="数据库类型" prop="dbType">
          <el-select v-model="queryParams.dbType">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in dbTypeList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测试连接状态" prop="connectStatus">
          <el-select v-model="queryParams.connectStatus">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in connectStatusList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept> -->
        <el-form-item label="IP地址" prop="dbIp">
          <common-input
            v-model="queryParams.dbIp"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="端口" prop="dbPort">
          <common-input-number
            v-model="queryParams.dbPort"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="来源" prop="ext1">
          <el-select v-model="queryParams.ext1">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="自动发现" value="1"></el-option>
            <el-option label="手动添加" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="principal">
          <common-input
            v-model="queryParams.principal"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
      </el-form>
    </common-search>
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:dbinfo:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          icon="el-icon-download"
          @click="importShow"
          v-hasPermi="['datascan:dbinfo:import']"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="changeUserStatus">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            :loading="exportLoading"
            class="btn-color-hover-white"
            v-hasPermi="['datascan:dbinfo:export']"
            >导出<commonIcon
              iconName="el-icon-arrow-down el-icon--right"
              iconType="icon"
              :iconSize="12"
              isStyle
            ></commonIcon>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="xlsx">XLSX</el-dropdown-item>
            <el-dropdown-item command="xls">XLS</el-dropdown-item>
            <el-dropdown-item command="html">HTML</el-dropdown-item>
            <el-dropdown-item command="xml">XML</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete()"
          :disabled="!showBatch"
          v-hasPermi="['datascan:dbinfo:remove']"
          >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          icon="el-icon-edit"
          @click="updatePwd()"
          :disabled="!showBatch"
          v-hasPermi="['datascan:dbinfo:remove']"
          >批量修改密码
        </el-button>
      </el-col>
    </el-row>
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      row-key="dbId"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="业务系统"
        align="left"
        prop="applicationSystem"
        show-overflow-tooltip
        fixed
      />
      <el-table-column label="数据库名" prop="dbName" show-overflow-tooltip />
      <!-- <el-table-column
        label="数据库组"
        prop="boundNames"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="数据库类型"
        align="left"
        width="120"
        prop="dbType"
      >
        <template slot-scope="scope">
          {{ scope.row.dbType }}
        </template>
      </el-table-column>
      <el-table-column
        label="IP地址"
        align="left"
        prop="dbIp"
        show-overflow-tooltip
      />
      <el-table-column label="端口" align="left" prop="dbPort" width="80" />
      <el-table-column
        label="实例名/服务名"
        align="left"
        prop="serviceName"
        width="160"
        show-overflow-tooltip
      />
      <el-table-column
        label="用户名"
        align="left"
        prop="dbAccount"
        show-overflow-tooltip
      />
      <el-table-column
        label="负责人"
        align="left"
        prop="principal"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="来源"
        align="center"
        prop="sourceType"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag type="info" v-if="row.ext1 === '1'">自动发现</el-tag>
          <el-tag type="warning" v-if="row.ext1 === '0'">手动添加</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="测试连接状态"
        align="center"
        prop="connectStatusName"
        width="130"
      >
        <template slot-scope="scope">
          <common-table-tooltip :tips="scope.row.connectResult">
            <el-tag
              v-if="scope.row.connectStatus !== null"
              :type="scope.row.connectStatus === 0 ? 'success' : 'danger'"
              style="cursor: pointer"
              effect="plain"
            >
              {{ scope.row.connectStatusName }}
            </el-tag>
          </common-table-tooltip>
        </template>
      </el-table-column>

      <!--      <el-table-column label="连接结果" prop="connectResult"/>-->
      <el-table-column
        label="操作"
        align="left"
        width="185"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button  disabled type="text" @click="scan(scope.row.dbId)">立即扫描</el-button> -->
          <el-button
            type="text"
            @click="testConn(scope.row.dbId)"
            v-hasPermi="['datascan:dbinfo:connection']"
            >测试连接
          </el-button>
          <el-button type="text" @click="dataDistribution(scope.row.dbId)"
            >数据分布
          </el-button>
          <el-dropdown @command="moreTool(scope.row, $event)">
            <span
              class="el-dropdown-link"
              style="cursor: pointer; margin-left: 8px; font-size: 12px"
              :style="{ '--theme-color': systemInfo.theme }"
              v-hasPermi="[
                'datascan:column:update',
                'datascan:dbinfo:edit',
                'datascan:dbinfo:remove',
              ]"
            >
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="size">
              <el-dropdown-item
                command="updatePwd"
                v-if="
                  scope.row.dbType !== 'hive' && scope.row.dbType !== 'hbase'
                "
                v-hasPermi="['datascan:dbinfo:edit']"
                >修改密码
              </el-dropdown-item>
              <el-dropdown-item
                command="edit"
                v-hasPermi="['datascan:dbinfo:edit']"
                >编辑
              </el-dropdown-item>
              <el-dropdown-item
                command="delete"
                v-hasPermi="['datascan:dbinfo:remove']"
                >删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handleList"
    />
    <!--  修改密码对话框-->
    <common-edit-dialog
      title="修改密码"
      @cancel="closeDialog"
      @submit="submit"
      :visible="isShow"
      :button-loading="buttonLoading"
      width="400px"
    >
      <el-form
        ref="passwordForm"
        :model="passwordForm"
        :rules="rules1"
        label-width="73px"
        @submit.native.prevent
      >
        <el-form-item label="修改密码" prop="dbPassword">
          <common-pwd-input
            placeholder="请输入"
            style="width: 100%"
            v-model="passwordForm.dbPassword"
          ></common-pwd-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="dbPasswordConfirm">
          <common-pwd-input
            placeholder="请输入"
            style="width: 100%"
            v-model="passwordForm.dbPasswordConfirm"
          ></common-pwd-input>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
    <!-- 添加或编辑数据库信息对话框 -->
    <AddDialog
      ref="AddDialog"
      @flushedList="handleList"
      :businessCodeList="businessCodeList"
    ></AddDialog>
    <template v-if="dataDistributionOpen">
      <DataDistribution
        ref="DataDistribution"
        @close="closeDataDistribution()"
        :dataId="dataId"
      ></DataDistribution>
    </template>
    <common-upload-dialog
      download-path="system/alarm/code/downFileByemplateName"
      upload-path="/datascan/b/dbinfo/importData"
      template-name="databaseTemplate.xls"
      report-path="/datascan/b/dbinfo/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="handleList"
    />
  </common-list>
</template>

<script>
import BaseIndex from "@/mixins/BaseIndex";
import {
  queryPageList,
  del,
  testConnection,
  scan,
  updateTypeAndLevel,
  updatePassword,
  selectAllDept,
  queryUserList,
  batchUpdatePassword,
  queryBusinessList,
} from "@/api/datascan/dbinfo/info";
import { queryGroupList } from "@/api/datascan/dbgroup/group";
import { queryListByTypeCode } from "@/api/datascan/scanresults/column";
import { encode } from "@/utils/aesUtils";
import BaseList from "@/mixins/BaseList";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";
import AddDialog from "./components/addDialog";
import DataDistribution from "./components/dataDistribution";
import CommonIcon from "@/components/CommonIcon";
export default {
  name: "Info",
  components: { AddDialog, DataDistribution, CommonIcon },
  mixins: [BaseList, BaseIndex],
  data() {
    const checkConsistent = (rule, value, callback) => {
      if (value !== this.passwordForm.dbPassword) {
        callback(new Error("两次密码不一致！"));
      } else {
        callback();
      }
    };
    return {
      dataId: "",
      userInfo: null,
      needScanDbLabel: "",
      list: [],
      isShow: false,
      dbTypeList: [], // 数据库类型
      dbGroupList: [],
      connectStatusList: [
        {
          label: "正常",
          value: 0,
        },
        {
          label: "网络异常",
          value: 1,
        },
        {
          label: "权限异常",
          value: 2,
        },
        {
          label: "其他",
          value: 3,
        },
      ], // 状态
      key: "dbId",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: null,
        dbType: null,
        dbGroupId: null,
        connectStatus: null,
        serviceName: null,
        dbPort: null,
        dbIp: null,
        deptIds: null,
        ext1: null,
        principal: null,
        applicationSystem: null,
      }, // 查询参数
      rules1: {
        dbPassword: [
          { required: true, message: "请输入数据库密码", trigger: "blur" },
        ],
        dbPasswordConfirm: [
          { required: true, validator: checkConsistent, trigger: "blur" },
        ],
      },
      passwordForm: {
        dbId: null,
        dbPassword: null,
        dbPasswordConfirm: null,
      },
      allDepList: [],
      userList: [],
      valueConsistsOf: "ALL",
      currentParent: 4,
      singleDeptList: [],
      deptListParams: [],
      buttonLoading: false,
      comfirmLoading: false,
      businessCodeList: [],
      initPort: null,
      initIp: null,
      dataDistributionOpen: false,
      exportLoading: false,
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  mounted() {
    this.getDataSourceTypeList();
    this.getGroupList();
    this.selectAllDept();
    this.queryUserList();
    this.queryBusinessCodeList();
    this.handleList();
  },

  methods: {
    changeUserStatus(data) {
      this.exportLoading = true;
      this.download(
        "/datascan/b/dbinfo/exportForm",
        {
          ...this.queryParams,
          pageSize: 10000,
          exportType: data,
        },
        `数据库资产${new Date().getTime()}.${data}`,
        1800000
      ).finally(() => {
        this.exportLoading = false;
      });
    },

    dataDistribution(id) {
      this.dataId = id;
      this.dataDistributionOpen = true;
      // this.$refs.DataDistribution.show();
    },
    closeDataDistribution() {
      this.dataDistributionOpen = false;
    },
    //获取业务系统列表
    queryBusinessCodeList() {
      queryBusinessList().then((res) => {
        if (res && res.code === 200) {
          this.businessCodeList = res.data;
        } else {
          this.businessCodeList = [];
        }
      });
    },
    getLoading() {
      this.loading = true;
    },
    getCheckedDeptId(val) {
      this.form.deptId = val;
    },

    // getDeptList(list) {
    //   this.deptListParams = list;
    //   this.singleDeptList = getSingleArray(list);

    // },
    // getDeptId(val) {
    //   this.queryParams.deptIds = val;
    // },
    // getDeptName(val) {
    //   let dept = this.singleDeptList.find((item) => item.id === val.toString());
    //   if (dept) return getFullDept(dept.fulllabel);
    // },

    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      // this.$refs.commonDept.clearDept();
    },

    //导入
    importShow() {
      this.$refs.uploadDialog.show();
    },

    reset() {
      this.passwordForm.dbId = "";
      this.passwordForm.dbPassword = "";
      this.passwordForm.dbPasswordConfirm = "";
    },
    updatePwd(row) {
      let isNoPwa = false;
      this.list.map((item) => {
        if (this.ids.includes(item.dbId)) {
          if (item.dbType === "hive" || item.dbType === "hbase") {
            isNoPwa = true;
          }
        }
      });
      if (isNoPwa) {
        return this.$GlobalErrorConfirm(
          "批量修改密码失败",
          "hive或hbase的数据库类型不可修改密码,请重新操作"
        );
      }

      this.isShow = true;
      if (row?.dbId) {
        this.passwordForm.dbPassword = row.dbPassword || "";
        this.passwordForm.dbId = row.dbId;
        this.passwordForm.dbName = row.dbName;
        this.passwordForm.dbType = row.dbType;
        this.passwordForm.dbIp = row.dbIp;
        this.passwordForm.dbPort = row.dbPort;
        this.passwordForm.dbAccount = row.dbAccount;
        this.passwordForm.needScanDb = row.needScanDb;
        this.passwordForm.serviceName = row.serviceName;
        this.passwordForm.dbGroupIds = row.dbGroupIds;
      } else {
        this.passwordForm.dbId = this.ids;
      }
    },
    closeDialog() {
      this.isShow = false;
      this.reset();
    },

    handleList() {
      this.loading = true;
      this.getList()
        .then(({ list, total }) => {
          this.list = list;
          this.total = total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    submit() {
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (Array.isArray(this.passwordForm.dbId)) {
            const params = {
              ids: this.passwordForm.dbId.join(","),
              dbPassword: encode(this.passwordForm.dbPassword) || "",
            };
            batchUpdatePassword(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("修改成功");
                  this.reset();
                  this.isShow = false;
                } else {
                  this.$GlobalErrorConfirm("修改失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            const params = {
              dbId: this.passwordForm.dbId,
              dbPassword: encode(this.passwordForm.dbPassword) || "",
              // dbName: this.passwordForm.dbName,
              // dbType: this.passwordForm.dbType,
              // dbIp: this.passwordForm.dbIp,
              // dbPort: this.passwordForm.dbPort,
              // dbAccount: this.passwordForm.dbAccount,
              // needScanDb: this.passwordForm.needScanDb,
              // serviceName: this.passwordForm.serviceName,
              // dbGroupIds: this.passwordForm.dbGroupIds,
            };
            updatePassword(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("修改成功");
                  this.reset();
                  this.isShow = false;
                } else {
                  this.$GlobalErrorConfirm("修改失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },

    /** 查询数据库信息列表 */
    getList() {
      return new Promise((resolve, reject) => {
        queryPageList(this.queryParams).then((res) => {
          if (res && res.code === 200) {
            resolve({
              total: res.data.totalCount,
              list: res.data.dataList.reduce((r, c) => {
                let csobj = this.connectStatusList.find(
                  (cs) => cs.value === c.connectStatus
                );
                c.connectStatusName = csobj ? csobj.label : "";
                // c.deptName = this.getDeptName(c.deptId || "");
                r.push(c);
                return r;
              }, []),
            });
          } else {
            resolve({
              total: 0,
              list: [],
            });
            this.handleListTips(res);
          }
        });
      });
    },

    del(id) {
      return new Promise((resolve, reject) => {
        del({ dbIds: id })
          .then((res) => {
            resolve(res);
          })
          .catch((res) => {
            reject(res);
          });
      });
    },

    moreTool(row, operate) {
      if (operate === "updatePwd") {
        this.updatePwd(row);
      }

      if (operate === "edit") {
        this.handleEdit(row);
      }
      if (operate === "delete") {
        this.handleDelete(row.dbId);
      }
    },

    scan(id) {
      this.$confirm("您确定要扫描吗？", "扫描", {
        confirmButtonText: "扫描",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        scan({ dbId: id }).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("操作成功");
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        });
      });
    },

    testConn(id) {
      this.$confirm("您确定要测试这个数据库吗?", "测试连接", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            testConnection({
              dbId: id,
            }).then((res) => {
              instance.confirmButtonLoading = false;
              done();
              setTimeout(() => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("连接成功");
                } else {
                  this.$GlobalErrorConfirm("连接失败", res.msg);
                }
              }, 500);
              this.handleList();
            });
          } else {
            done();
          }
        },
      });
    },

    getDataSourceTypeList() {
      queryListByTypeCode().then((res) => {
        if (res && res.code === 200) {
          this.dbTypeList = res.data.dataList.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.value,
            });
            return r;
          }, []);
        } else {
          this.dbTypeList = [];
        }
      });
    },
    getGroupList() {
      queryGroupList({}).then((res) => {
        if (res && res.code === 200) {
          this.dbGroupList = res.data.dataList.reduce((r, c) => {
            r.push({
              label: c.groupName,
              value: c.id,
              deptName: c.deptName,
              deptId: c.deptId,
            });
            return r;
          }, []);
        }
      });
    },

    selectAllDept() {
      selectAllDept().then((res) => {
        if (res && res.code === 200) {
          this.allDepList = res.data.dataList;
          let setDisabled = (data) => {
            if (data.length > 0) {
              data.forEach((f) => {
                f.id = f.value || f.key;
                f.label = f.departName;
                if (f.children && f.children.length > 0) {
                  setDisabled(f.children);
                } else {
                  delete f.children;
                }
              });
            }
          };
          setDisabled(this.allDepList);
        }
      });
    },

    queryUserList() {
      queryUserList().then((res) => {
        if (res && res.code === 200) {
          this.userList = res.data.dataList;
        } else {
          this.userList = [];
        }
      });
    },

    changeSelect(val) {
      let index = this.userList.findIndex((f) => f.userName === val);
      if (index > -1) this.form.telephone = this.userList[index].phonenumber;
    },
    handleAdd() {
      this.$refs.AddDialog.show();
    },
    handleEdit(row) {
      this.$refs.AddDialog.show(row);
    },
  },
};
</script>
<style scoped lang="scss">
.el-dropdown-link {
  color: var(--theme-color);
}

::v-deep .edit-form {
  .el-select {
    .el-tag {
      .el-tag__close {
        color: #fff !important;
        margin-right: 3px;
      }
    }
  }
}

::v-deep .common-input-number {
  width: 100%;
}

.el-dropdown-menu__item {
  font-size: 12px;
}

::v-deep .vue-treeselect__control {
  .vue-treeselect__x-container {
    display: none;
  }

  &:hover {
    //&代表上级的.vue-treeselect__control
    .vue-treeselect__x-container {
      display: table-cell;
    }
  }

  padding-left: 0;
  .vue-treeselect__placeholder {
    margin-left: 10px;
  }
  .vue-treeselect__multi-value {
    margin-bottom: 0;
    padding: 2px 0;

    .vue-treeselect__multi-value-item-container {
      line-height: 19px;
      font-size: 12px;
      margin: 2px 0 2px 6px;
      padding: 0;
    }

    .vue-treeselect__multi-value-item {
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      color: #909399;
      display: flex;
      align-items: center;
      padding-right: 1px;

      .vue-treeselect__value-remove {
        width: 12px !important;
        height: 12px !important;
        margin-right: 3px;
        color: #fff;
        border-left: none;
        background-color: #c0c4cc;
        border-radius: 50%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;

        &:hover {
          background-color: #909399;
        }
      }
    }
  }
}
::v-deep .el-table .el-tag--info.el-tag {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #d9ecff;
}
.btn-color-hover-white:hover,
.btn-color-hover-white:focus {
  .iconfont {
    color: #fff !important;
  }
}
</style>
